package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*" , filterName = "loginFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截器拦截到了 url:{}", requestURI);
        String[] uris = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/upload",
                "/common/download",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        boolean checkURI = checkURI(requestURI, uris);
//        如果返回true就不拦截直接放行
        if (checkURI){
            filterChain.doFilter(request,response);
            return;
        }

        Long employeeID = (Long) request.getSession().getAttribute("employee");
//        判断是否登录
        if (employeeID != null ){
            log.info("管理端用户已登录");
            BaseContext.setThreadLocal(employeeID);
            filterChain.doFilter(request,response);
            return;
        }
        Object userId = request.getSession().getAttribute("user");
//        判断是否登录
        if (userId != null ){
            log.info("移动端用户已登录");
            BaseContext.setThreadLocal((Long) userId);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

//    判断是否需要被拦截
    private boolean checkURI(String requestURI, String[] uris) {
        for (String uri : uris) {
            boolean flag = PATH_MATCHER.match(uri, requestURI);
            if (flag){
                return true;
            }
        }
       return false;
    }


}
